package com.ruoyi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class RuoYiApplication {
    private static JFrame mainFrame;
    private static JTextArea consoleOutputArea;
    private static JPanel consolePanel;
    private static JPopupMenu contextMenu;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            System.setProperty("java.awt.headless", "false");
            setGlobalFont(new Font("黑体", Font.PLAIN, 14));
            initializeGUI();
        });

        new Thread(() -> {
            ConfigurableApplicationContext context = SpringApplication.run(RuoYiApplication.class, args);
            SwingUtilities.invokeLater(() -> {
                updateGUIForSystemRunning();
                openBrowser("http://localhost:55555");
            });
        }).start();
    }

    private static void initializeGUI() {
        mainFrame = new JFrame("知微时代批量搭建系统");
        mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        mainFrame.setSize(320, 150);
        mainFrame.setLocationRelativeTo(null);

        initContextMenu();

        mainFrame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    contextMenu.show(mainFrame, e.getX(), e.getY());
                }
            }
        });

        JPanel loadingPanel = new JPanel(new BorderLayout());
        loadingPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JLabel titleLabel = new JLabel("系统启动中", JLabel.CENTER);
        titleLabel.setFont(new Font("黑体", Font.BOLD, 28));

        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);

        loadingPanel.add(titleLabel, BorderLayout.NORTH);
        loadingPanel.add(progressBar, BorderLayout.SOUTH);
        mainFrame.add(loadingPanel);

        initializeConsoleComponents();
        redirectErrorOutput();

        mainFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                confirmExit();
            }
        });

        mainFrame.setVisible(true);
    }

    private static void initContextMenu() {
        contextMenu = new JPopupMenu();
        JMenuItem toggleConsoleItem = new JMenuItem("显示/隐藏控制台");
        toggleConsoleItem.addActionListener(e -> toggleConsoleVisibility());
        contextMenu.add(toggleConsoleItem);
    }

    private static void toggleConsoleVisibility() {
        boolean show = !consolePanel.isVisible();
        consolePanel.setVisible(show);

        // 重新布局并调整窗口大小
        updateGUIForSystemRunning();
    }

    private static void initializeConsoleComponents() {
        consoleOutputArea = new JTextArea(10, 50);
        consoleOutputArea.setEditable(false);
        consoleOutputArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
        consoleOutputArea.setForeground(Color.RED);

        JScrollPane scrollPane = new JScrollPane(consoleOutputArea);

        consolePanel = new JPanel(new BorderLayout());
        consolePanel.add(scrollPane, BorderLayout.CENTER);
        consolePanel.setVisible(false);
    }

    private static void redirectErrorOutput() {
        OutputStream err = new OutputStream() {
            private StringBuilder buffer = new StringBuilder();

            @Override
            public void write(int b) throws IOException {
                buffer.append((char) b);
                if (b == '\n') {
                    flushBuffer();
                }
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                buffer.append(new String(b, off, len));
                if (buffer.indexOf("\n") >= 0) {
                    flushBuffer();
                }
            }

            private void flushBuffer() {
                String text = buffer.toString();
                buffer.setLength(0);
                SwingUtilities.invokeLater(() -> {
                    consoleOutputArea.append(text);
                    consoleOutputArea.setCaretPosition(consoleOutputArea.getDocument().getLength());
                });
            }
        };

        System.setErr(new PrintStream(err, true));
    }

    private static void updateGUIForSystemRunning() {
        mainFrame.getContentPane().removeAll();

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 状态标签
        JLabel statusLabel = new JLabel("系统运行中", JLabel.CENTER);
        statusLabel.setFont(new Font("黑体", Font.BOLD, 24));
        mainPanel.add(statusLabel, BorderLayout.NORTH);

        // 添加浏览器访问按钮
        JButton openBrowserButton = new JButton("访问系统");
        openBrowserButton.setFont(new Font("黑体", Font.PLAIN, 16));
        openBrowserButton.addActionListener(e -> openBrowser("http://localhost:55555"));

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(openBrowserButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 控制台面板 - 动态添加
        if(consolePanel.isVisible()) {
            mainPanel.add(consolePanel, BorderLayout.CENTER);
        }

        mainFrame.add(mainPanel);

        // 动态计算理想尺寸
        Dimension preferredSize = consolePanel.isVisible()
                ? new Dimension(600, 400)  // 控制台显示时的尺寸
                : new Dimension(320, 150); // 控制台隐藏时的紧凑尺寸

        mainFrame.setPreferredSize(preferredSize);
        mainFrame.pack();
    }

    private static void setGlobalFont(Font font) {
        UIManager.put("Button.font", font);
        UIManager.put("Label.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("ComboBox.font", font);
        UIManager.put("ProgressBar.font", font);
        UIManager.put("MenuItem.font", font);
    }

    private static void openBrowser(String url) {
        if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
            try {
                Desktop.getDesktop().browse(new URI(url));
            } catch (IOException | URISyntaxException e) {
                System.err.println("无法打开浏览器: " + e.getMessage());
                JOptionPane.showMessageDialog(mainFrame,
                        "无法打开浏览器: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            System.err.println("当前系统不支持自动打开浏览器");
            JOptionPane.showMessageDialog(mainFrame,
                    "当前系统不支持自动打开浏览器",
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private static void confirmExit() {
        int result = JOptionPane.showConfirmDialog(
                mainFrame,
                "确定要退出系统吗？",
                "退出确认",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE
        );

        if (result == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }
}